package com.fyw.kotlin.ui

import android.content.Context
import android.os.Bundle
import android.text.TextUtils
import android.view.View
import cn.bmob.v3.BmobUser
import com.fyw.kotlin.R
import com.fyw.kotlin.base.BaseActivity
import kotlinx.android.synthetic.main.activity_register.*
import cn.bmob.v3.exception.BmobException
import cn.bmob.v3.listener.SaveListener


/**
 * 注册界面
 * Created by FYW on 2017/9/28.
 */
class RegisterActivity : BaseActivity(), View.OnClickListener {

    private var registerNameStr: String = ""
    private var registerPwdStr: String = ""
    private var registerConfirmPwdStr: String = ""

    override fun initParam(param: Bundle?) {
    }

    override fun bindLayout(): Int {
        return R.layout.activity_register
    }

    override fun initView(view: View) {
        registerBtn.setOnClickListener(this)
    }

    override fun doBusiness(mContext: Context) {
    }

    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.registerBtn -> {                                                                   //注册按钮点击事件

                registerNameStr = registerNameEt.text.toString()                                    //用户名
                registerPwdStr = registerPwdEt.text.toString()                                      //密码
                registerConfirmPwdStr = registerConfirmPwdEt.text.toString()                        //确认密码

                when {

                    TextUtils.isEmpty(registerNameStr) -> showToast("请输入用户名")
                    TextUtils.isEmpty(registerPwdStr) -> showToast("请输入密码")
                    TextUtils.isEmpty(registerConfirmPwdStr) -> showToast("请输入确认密码")
                    registerPwdStr != registerConfirmPwdStr -> showToast("两次输入的密码不一致")

                    else -> {

                        loadingDialog.setMessage("正在提交注册信息").show()                         //弹出等待对话框

                        val myUser = BmobUser()
                        myUser.setPassword(registerPwdStr)
                        myUser.username = registerNameStr

                        //注意：不能用save方法进行注册
                        myUser.signUp(object : SaveListener<BmobUser>() {
                            override fun done(s: BmobUser, e: BmobException?) {

                                loadingDialog.dismiss()                                             //关闭等待对话框

                                if (e == null) {
                                    showToast("注册成功")
                                    finish()
                                } else {
                                    showToast("注册失败")
                                }
                            }
                        })

                    }
                }
            }
        }
    }
}